package com.ruoyi.sale.service.impl;

import java.util.List;
import java.util.stream.Collectors;

import com.ruoyi.dto.CouponDto;
import com.ruoyi.sale.domain.MallCouponProductRegionRelation;
import com.ruoyi.sale.domain.MallCouponProductRelation;
import com.ruoyi.sale.mapper.MallCouponProductRegionRelationMapper;
import com.ruoyi.sale.mapper.MallCouponProductRelationMapper;
import com.ruoyi.shopping.domain.MallRegions;
import com.ruoyi.vo.CouponVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.sale.mapper.MallCouponMapper;
import com.ruoyi.sale.domain.MallCoupon;
import com.ruoyi.sale.service.IMallCouponService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 优惠券Service业务层处理
 *
 * @author cws
 * @date 2024-11-21
 */
@Service
@Slf4j
public class MallCouponServiceImpl implements IMallCouponService {
    @Autowired
    private MallCouponMapper mallCouponMapper;

    @Autowired
    private MallCouponProductRelationMapper mallCouponProductRelationMapper;

    @Autowired
    private MallCouponProductRegionRelationMapper mallCouponProductRegionRelationMapper;

    /**
     * 查询优惠券
     *
     * @param id 优惠券主键
     * @return 优惠券
     */
    @Override
    public CouponVo selectMallCouponById(Long id) {
        CouponVo couponVo = new CouponVo();
        MallCoupon mallCoupon = mallCouponMapper.selectMallCouponById(id);
        BeanUtils.copyProperties(mallCoupon, couponVo);
        if (mallCoupon.getUseType().equals(1L)) {
            List<MallCouponProductRegionRelation> regionsList = mallCouponProductRegionRelationMapper.getRegionByCopuponId(id);
            couponVo.setRegionRelations(regionsList);
        } else if (mallCoupon.getUseType().equals(2L)) {
            List<MallCouponProductRelation> list = mallCouponProductRelationMapper.getProductRelations(id);
            couponVo.setProductRelations(list);
        }
        return couponVo;
    }

    /**
     * 查询优惠券列表
     *
     * @param mallCoupon 优惠券
     * @return 优惠券
     */
    @Override
    public List<MallCoupon> selectMallCouponList(MallCoupon mallCoupon) {
        return mallCouponMapper.selectMallCouponList(mallCoupon);
    }

    /**
     * 新增优惠券
     * cws
     *
     * @param couponDto 优惠券
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertMallCoupon(CouponDto couponDto) {
        try {
            this.check(couponDto);
            // 1. 拷贝
            MallCoupon mallCoupon = new MallCoupon();
            BeanUtils.copyProperties(couponDto, mallCoupon);
            mallCouponMapper.insertMallCoupon(mallCoupon);
            Long id = mallCoupon.getId();
            // 2. 判断优惠券类型
            if (couponDto.getUseType().equals(1L)) { // 地州添加
                handleRegionRelations(couponDto, id);
            } else if (couponDto.getUseType().equals(2L)) { // 商品添加
                handleProductRelations(couponDto, id);
            }
            return 1;
        } catch (Exception e) {
            // 记录异常日志
            log.error("插入优惠券失败", e);
            throw e;
        }
    }

    private void handleRegionRelations(CouponDto couponDto, Long id) {
        List<MallCouponProductRegionRelation> regionRelations = couponDto.getRegionRelations();
        if (regionRelations == null || regionRelations.isEmpty()) {
            throw new RuntimeException("请选择地区并添加");
        }
        regionRelations.forEach(item -> {
            item.setCouponId(id);
            mallCouponProductRegionRelationMapper.insertMallCouponProductRegionRelation(item);
        });
    }

    private void handleProductRelations(CouponDto couponDto, Long id) {
        List<MallCouponProductRelation> productRelations = couponDto.getProductRelations();
        if (productRelations == null || productRelations.isEmpty()) {
            throw new RuntimeException("请选择商品并添加");
        }
        productRelations.forEach(item -> {
            item.setCouponId(id);
            mallCouponProductRelationMapper.insertMallCouponProductRelation(item);
        });
    }

    //校验方法
    private void check(CouponDto couponDto) {
//       如果当前时间大于优惠局卷的结束时间，则抛出异常
        if (couponDto.getEndTime().getTime() < System.currentTimeMillis()) {
            throw new RuntimeException("优惠券开始时间必须大于当前时间");
        }
//        领取时间必须大于当前时间
        if (couponDto.getEnableTime().getTime() < System.currentTimeMillis()) {
            throw new RuntimeException("优惠券领取时间必须大于当前时间");
        }
//        限领取数据不能大于总发
        if (couponDto.getPerLimit() > couponDto.getPublishCount()) {
            throw new RuntimeException("优惠券领取数量不能大于总发行数量");
        }
    }

    /**
     * 修改优惠券
     *
     * @param mallCoupon 优惠券
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateMallCoupon(CouponDto couponDto) {
        this.check(couponDto);
        MallCoupon mallCoupon = new MallCoupon();
        BeanUtils.copyProperties(couponDto, mallCoupon);
        mallCouponMapper.updateMallCoupon(mallCoupon);
        if (couponDto.getUseType().equals(1L)) {
            //查询是否存在
            int count = mallCouponProductRegionRelationMapper.selectProductRegionRelationCoutByCouponId(couponDto.getId());
            if (count > 0) {
                List<MallCouponProductRegionRelation> regionRelations = couponDto.getRegionRelations();
                regionRelations.forEach(item -> {
                    mallCouponProductRegionRelationMapper.updateMallCouponProductRegionRelation(item);
                });
            } else {
                List<MallCouponProductRegionRelation> regionRelations = couponDto.getRegionRelations().stream().map(item -> {
                    item.setCouponId(couponDto.getId());
                    return item;
                }).collect(Collectors.toList());
                regionRelations.forEach(item -> {
                    mallCouponProductRegionRelationMapper.insertMallCouponProductRegionRelation(item);
                });
            }
        } else if (couponDto.getUseType().equals(2L)) {
            int count = mallCouponProductRelationMapper.selectProductRelationCoutByCouponId(couponDto.getId());
            if (count > 0) {
                List<MallCouponProductRelation> productRelations = couponDto.getProductRelations();
                productRelations.forEach(item -> {
                    mallCouponProductRelationMapper.updateMallCouponProductRelation(item);
                });
            } else {
                List<MallCouponProductRelation> productRelations = couponDto.getProductRelations().stream().map(item -> {
                    item.setCouponId(couponDto.getId());
                    return item;
                }).collect(Collectors.toList());
                productRelations.forEach(item -> {
                    mallCouponProductRelationMapper.insertMallCouponProductRelation(item);
                });
            }
        }
        return 1;
    }

    /**
     * 批量删除优惠券
     *
     * @param ids 需要删除的优惠券主键
     * @return 结果
     */
    @Override
    public int deleteMallCouponByIds(Long[] ids) {
        int i = mallCouponMapper.deleteMallCouponByIds(ids);
//        删除绑定关系
        for (Long id : ids) {
//            删除地区绑定
            mallCouponProductRegionRelationMapper.deleteByProductRegionRelationByCouponId(id);
//        删除商品绑定
            mallCouponProductRelationMapper.deleteByProductRelationByCouponId(id);
        }
        return i;
    }

    /**
     * 删除优惠券信息
     *
     * @param id 优惠券主键
     * @return 结果
     */
    @Override
    public int deleteMallCouponById(Long id) {
        return mallCouponMapper.deleteMallCouponById(id);
    }
}
